#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using std::string;
class HttpRequest
{
public:
    HttpRequest(){};
    ~HttpRequest(){};

    //分析获取的数据
    void parse(string buff)
    {
        //按空格划分
        std::istringstream in(buff);
        in >> _method >> _url >> _version;

        //资源路径
        _path = "./wwwroot";//root路径
        if (_url == "/")
            _path += "/html/index.html";
        else
            _path += _url;
        
        //访问资源大小
        struct stat st;
        if(stat(_path.c_str(), &st) < 0)
        {
            //打开文件失败  ----  打开404 web
            stat("./wwwroot/html/NotFound.html", &st);
            _size = st.st_size;
        }
        else
            _size = st.st_size;

        //访问资料类型 text html..
        size_t pos = _url.rfind('.');
         //查找失败
        if (pos == std::string::npos)
            _suffix = ".html";
        else
            _suffix = _url.substr(pos);
    }

    //回应 网页
    string respose()
    {
        //状态行
        string status = "HTTP/1.1 200 ok\r\n";

        //响应报头
        string header_str = content_type();//资源数据类型
        header_str += ("Content-Length: " + std::to_string(_size + 1) + "\r\n");//Content-Length
        
        //空行
        header_str += "\r\n";

        //响应正文
        string body;//存放网页信息
        body.resize(_size + 1);
        int fd = open(_path.c_str(), O_RDONLY);
        if (fd < 0)
        {
            fd = open("./wwwroot/html/NotFound.html", O_RDONLY);
        }
        if (read(fd, &body[0], _size) < 0)//访问失败
        {
            perror("read web");
            exit(1);
        }

        //响应内容
        string respose = (status + header_str + body);

        return respose;
    }
private:
    //返回Content-Tyepe
    string content_type(void)
    {
        string ct = "Content-Type: ";
        if (_suffix == ".html") //纯html网页
            ct += "text/html";
        else if (_suffix == ".png") //png格式的图片
            ct += "image/png";
        else if (_suffix == ".jpg") //jpg格式的图片
            ct += "image/jpeg";
        ct += "\r\n";
        return ct;
    }
public:
    string _method;
    string _url;
    string _version;
    string _path;//访问资源路径
    size_t _size;//访问资源大小
    string _suffix;//访问资料类型 text html..
};